import { orderInfo, saveJsonData } from '@/services/ant-design-pro/api';
import { useParams } from '@@/exports';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { ProFormDigit } from '@ant-design/pro-form/lib';
import { Button, Col, message, Row, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import './index.less';
import useForm = ProForm.useForm;

interface ParamVo {
  length: number;
  lastHeight: number;
  width: number;
  height: number;
  num: number;
  gap: number;
  productNum: number;
  widthCount: number;
  lengthCount: number;
  diaphragmThickness: number;
  ll1: number;
  ll2: number;
  sideWidth: number;
  subHeight: number;
  model: string; //型号
  modelName: string; //型号
  date: string; //型号
  lastWidth: number;
  lastLength: number;
  landscapeHeight: number;
  landscapeLength: number;
  portraitLength: number;
  portraitHeight: number;
  type: number;
  llLength: number;
  llWidth: number;
  realLength: number;
  realWidth: number;

  aaLength: number;
  aaHeight: number;
  aaWidth: number;

  aLength: number;
  aWidth: number;
  aHeight: number;

  al1: number;
  aw1: number;

  al11: number;
  aw12: number;

  al2: number;
  aw2: number;

  al21: number;
  aw22: number;
}

const calc = (count: number, params: ParamVo) => {
  let widthCount = 1;
  let lengthCount = 1;
  let result = { countRad: 50, rad: 50, widthCount, lengthCount };
  while (lengthCount < count) {
    widthCount = Math.ceil(count / lengthCount);
    const temp = widthCount * lengthCount - count;
    const tempCount = Math.abs(widthCount - lengthCount);
    const gap = params.gap || 20;
    if (
      Math.abs(lengthCount - widthCount) <= gap &&
      lengthCount >= widthCount &&
      temp <= result.rad
    ) {
      if (temp === result.rad) {
        if (tempCount > result.countRad) {
          lengthCount++;
          continue;
        }
      }
      result.countRad = Math.abs(lengthCount - widthCount);
      result.rad = temp;
      result.widthCount = widthCount;
      result.lengthCount = lengthCount;
    }
    lengthCount++;
  }
  return result;
};

const types = [
  {
    name: '欧美达',
    calc,
  },
  {
    name: '永合电力机械有限公司',
    calc,
  },
];

const toNumber = (num: number, type: number = 0): number => {
  if (type === 1) {
    return Math.round(num);
  }
  if (`${num}`.indexOf('.') === -1) {
    return num;
  }
  return Number(num.toFixed(1));
};



const toNumberFloor = (num: number, type: number = 0): number => {
  if (type === 1) {
    return Math.round(num);
  }
  if (`${num}`.indexOf('.') === -1) {
    return num;
  }
  return Math.floor(num);
};

const toHeight = (num: number, type: number = 0): number => {
  if (type === 1) {
    if (`${num}`.indexOf('.') === -1) {
      return num + 0.5;
    }
    return Math.ceil(num);
  }
  return toNumber(num);
};

const toNumberFix = (num: number, type: number = 0): number => {
  if (`${num}`.indexOf('.') === -1) {
    return num + 0.5;
  }
  return toNumber(num);
};
const EditPage: React.FC = () => {
  const [form] = useForm();
  const [pageForm] = useForm();
  // orderInfo()
  const { id } = useParams();
  const initValues = {
    model: 'PJ-1012',
    length: 71,
    width: 28,
    realWidth: 28,
    realLength: 90,
    height: 90,
    num: 50,
    gap: 20,
    diaphragmThickness: 3,
    sideWidth: 5,
    productNum: 1,
    subHeight: 15,
    widthCount: 1,
    lengthCount: 1,
    ll1: 0,
    ll2: 0,
    lastHeight: 0,
    lastWidth: 0,
    lastLength: 0,
    landscapeHeight: 0,
    landscapeLength: 0,
    portraitLength: 0,
    portraitHeight: 0,
    type: 0,
    llLength: 0,
    llWidth: 0,
    aLength: 0,
    aWidth: 0,
    aHeight: 0,

    aaLength: 0,
    aaHeight: 0,
    aaWidth: 0,

    al1: 0,
    aw1: 0,
    al11: 0,
    aw12: 0,

    al2: 0,
    aw2: 0,
    al21: 0,
    aw22: 0,
  };
  const [select, setSelect] = useState(0);
  const [pageInfo, setPageInfo] = useState({ modelName: '', date: '' });

  function findSimilarItems(data) {
    // 创建深拷贝
    const result = data.map(item => ({...item}));

    // 按 productNum 分组
    const groups = {};
    result.forEach(item => {
      if (!groups[item.productNum]) {
        groups[item.productNum] = [];
      }
      groups[item.productNum].push(item);
    });

    // 检查每个分组中的元素
    Object.values(groups).forEach(group => {
      // 收集所有相近的值
      const similarGroups = new Map();

      // 第一次遍历：收集相近的值
      for (let i = 0; i < group.length; i++) {
        for (let j = i + 1; j < group.length; j++) {
          const item1 = group[i];
          const item2 = group[j];

          // 比较所有可能的组合
          const comparisons = [
            { val1: item1.aaLength, val2: item2.aaLength, type1: 'aaLength', type2: 'aaLength' },
            { val1: item1.aaLength, val2: item2.aaWidth, type1: 'aaLength', type2: 'aaWidth' },
            { val1: item1.aaWidth, val2: item2.aaLength, type1: 'aaWidth', type2: 'aaLength' },
            { val1: item1.aaWidth, val2: item2.aaWidth, type1: 'aaWidth', type2: 'aaWidth' }
          ];

          comparisons.forEach(comp => {
            const diff = Math.abs(comp.val1 - comp.val2);
            if (diff <= 20) {
              const key = `${comp.type1}-${comp.type2}-${Math.min(comp.val1, comp.val2)}`;
              if (!similarGroups.has(key)) {
                similarGroups.set(key, {
                  items: [],
                  type1: comp.type1,
                  type2: comp.type2,
                  values: []
                });
              }
              similarGroups.get(key).items.push(
                { item: item1, value: comp.val1, type: comp.type1 },
                { item: item2, value: comp.val2, type: comp.type2 }
              );
              similarGroups.get(key).values.push(comp.val1, comp.val2);
            }
          });
        }
      }

      // 第二次遍历：应用平均值
      for (const [_, group] of similarGroups) {
        const uniqueItems = [...new Set(group.items.map(x => x.item))];
        if (uniqueItems.length > 1) {
          const avgValue = Math.round(group.values.reduce((sum, val) => sum + val, 0) / group.values.length);

          // 更新所有相关项
          uniqueItems.forEach(item => {
            // 检查并更新aaLength
            if (group.items.some(x => x.item === item && x.type === 'aaLength')) {
              item.aLength = toNumberFloor(avgValue/10,item.type);
            }
            // 检查并更新aaWidth
            if (group.items.some(x => x.item === item && x.type === 'aaWidth')) {
              item.aWidth = toNumberFloor(avgValue/10,item.type);
            }
          });
        }
      }
    });

    return result;
  }

  const initCount = (initValues: ParamVo) => {
    if (initValues && (initValues.num || 0) > 0) {
      let paramNum = initValues.num || 10;
      if (paramNum < 2) {
        paramNum = 2;
      }
      console.log(`paramNum ${paramNum}`);
      const typeVal = types[initValues.type || 0];
      const { widthCount, lengthCount } = typeVal.calc(paramNum, initValues);
      let { width, diaphragmThickness, length, height, subHeight, sideWidth, type } = initValues;
      width = +(width || 0);
      diaphragmThickness = +(diaphragmThickness || 0);
      const ff1 = lengthCount > widthCount;
      const ff2 = length > width;
      const fff = (ff1 && ff2) || (!ff1 && !ff2);
      const realLength = fff ? width : length;
      const realWidth = !fff ? width : length;
      const ll1 = lengthCount * realLength + (lengthCount - 1) * diaphragmThickness;
      const ll2 = widthCount * realWidth + (widthCount - 1) * diaphragmThickness;
      const lastLength =
        Math.round(((ll1 / 10) * 10 + (type === 1 ? diaphragmThickness * lengthCount : 0)) / 10) *
        10;
      const lastWidth =
        Math.round(((ll2 / 10) * 10 + (type === 1 ? diaphragmThickness * widthCount : 0)) / 10) *
        10;
      // const fieldValues = form.getFieldsValue();
      let llLength = 0;
      let llWidth = 0;
      if (lastLength > lastWidth) {
        llLength = lengthCount;
        llWidth = widthCount;
      } else {
        llLength = widthCount;
        llWidth = lengthCount;
      }
      const fl1 = lastLength; //
      const fl2 = lastWidth;
      const flag = fl1 > fl2;
      const lfl1 = flag ? fl1 : fl2; //板材长度
      const lfl2 = flag ? fl2 : fl1; //板材宽度
      let wd1 = type === 1 ? lastLength - sideWidth : fl1 - sideWidth; //fl1 - sideWidth;
      let wd2 = type === 1 ? lastWidth - sideWidth : fl2 - sideWidth; //fl2 - sideWidth;
      // const top1Height =

      // if (flag) {
      //   wd1 = fl1 - sideWidth;
      //   wd2 = fl2 - sideWidth;
      // } else {
      //   wd2 = fl1 - sideWidth;
      //   wd1 = fl2 - sideWidth;
      // }
      const landscapeLength = wd1; // 横向隔板长度
      const lastHeight = toHeight(height / 10,type);
      const landscapeHeight = height - subHeight; // 横向隔板高度
      const portraitLength = wd2; // 纵向隔板长度
      const portraitHeight = height  - subHeight; // 纵向隔板高度
      const four1 = `${landscapeLength / 10}*${landscapeHeight / 10}=${lengthCount - 1}`;
      const four2 = `${portraitLength / 10}*${portraitHeight / 10}=${widthCount - 1}`;
      // const flag = ll1>ll2?lengthCount:lengthCount

      const aaLength =
        lastLength > lastWidth ? lastLength : lastWidth;
      const aaWidth =
        lastLength > lastWidth ? lastWidth : lastLength;
      const aaHeight = height;

      const aLength = toNumber(aaLength/10, type);
      const aWidth = toNumber(aaWidth/10, type);
      const aHeight = toHeight(aaHeight / 10, type);

      const al1 = landscapeLength > portraitLength ? landscapeLength / 10 : portraitLength / 10;
      const aw1 = landscapeLength > portraitLength ? landscapeHeight / 10 : portraitHeight / 10;
      const al11 =
        landscapeLength > portraitLength
          ? (ll1 > ll2 ? widthCount : lengthCount) - 1
          : (ll1 > ll2 ? widthCount : lengthCount) - 1;

      const al2 = landscapeLength > portraitLength ? portraitLength / 10 : landscapeLength / 10;
      const aw2 = landscapeLength > portraitLength ? portraitHeight / 10 : landscapeHeight / 10;
      const al21 = (ll1 > ll2 ? lengthCount : widthCount) - 1;
      return {
        ...initValues,
        // ...fieldValues,
        realLength,
        realWidth,
        widthCount,
        lengthCount,
        llLength,
        llWidth,
        ll1,
        lastHeight,
        ll2,
        lastLength,
        lastWidth,
        four1,
        four2,
        type,
        lfl1,
        lfl2,
        landscapeLength,
        landscapeHeight,
        portraitLength,
        portraitHeight,
        aLength,
        aWidth,
        aHeight,
        aaLength,
        aaHeight,
        aaWidth,
        al1,
        aw1,
        al11,
        al2,
        aw2,
        al21,
      };

      // setParams({ ...values, ...fieldValues, widthCount, lengthCount, ll1, ll2 });
    }
  };

  //@ts-ignore
  const val = initCount(initValues);
  const [params, setParams] = useState<ParamVo[]>([val]);
  const initData = async () => {
    if (id) {
      const result: any = await orderInfo(id);
      const json = JSON.parse(result.data.json_data);
      if (json) {
        const { modelName, date } = json || {};
        setParams(json?.params || []);
        setPageInfo({ modelName, date });
        form.setFieldValue('remark', json?.remark);
        form.setFieldsValue(json?.params[0]);
        pageForm.setFieldsValue({ modelName, date });
      }
    }
  };
  useEffect(() => {
    initData();
  }, [id]);
  useEffect(() => {
    window.onbeforeprint = () => {
      const node = document.getElementById('print-header');
      if (node !== null) node.style.display = 'block';
    };
    window.onafterprint = () => {
      const node = document.getElementById('print-header');
      if (node !== null) node.style.display = 'none';
    };
    // setParams(initCount(params))
  }, []);
  const merge = () => {
    console.log(params)
    const matchResult = findSimilarItems(params);
    console.log(matchResult)
    setParams([...matchResult]);
  };

  const refresh = () => {
    const result = [];
    for (let i = 0; i < params.length; i++) {
      result[i] = initCount(params[i]);
    }
    console.log(result);
    //@ts-ignore
    setParams(result);
  };

  const render = (params: ParamVo[]) => {
    const doms = params.map((param: ParamVo, index: number) => {
      const {
        model,
        productNum,
        num,
        lengthCount,
        realLength,
        realWidth,
        llLength,
        llWidth,
        width,
        diaphragmThickness,
        ll1,
        widthCount,
        ll2,
        length,
        height,
        aLength,
        aWidth,
        aHeight,
        al1,
        aw1,
        al11,
        al2,
        aw2,
        al21,
      } = param || {};
      // <div key={`${index}-item`}>
      //   <div className="print-header">
      //     asdasdasdasd
      //   </div>
      return (
        <>
        <Col
          key={`${index}-item`}
          className={`card-panel ${index % 2 === 0 ? 'even' : 'odd'} ${
            index > 1 ? 'top-line' : ''
          } ${select === index ? 'active' : ''}`}
          span={12}
          onClick={() => {
            setSelect(index);
            if (params[index]) {
              params[index].gap = params[index].gap || 20;
              form.setFieldsValue({ ...params[index] });
            }
          }}
        >
          {(index%9===0 || index%8===0) && index!==0 ? <Row className="block-panel"></Row>:<></>}
          <Row gutter={1}>
            <Col span={8} className="bold small-subtitle break-word">
              {model}
            </Col>
            <Col span={8} className="model-size sub-title">
              <span>{length}</span>
              <span className="mul">X</span>
              <span>{width}</span>
              <span className="mul">X</span>
              <span style={{ borderBottom: '1px solid black' }}>{height}</span>
            </Col>
            <Col span={8} className="sub-title">
              <span>{num}片</span>X<span className="ml5">{productNum}只</span>
            </Col>
          </Row>
          <Row className="mt10 sub-title" gutter={10}>
            <Col className="br5 border pd5 position-parent">
              <span>{lengthCount}</span>
              <span className="mul">X</span>
              <span>{widthCount}</span>
              <span className="mul">=</span>
              <span>{lengthCount * widthCount}</span>
              <span className="position top">{llLength}</span>
              <span className="position left">{llWidth}</span>
            </Col>

            {ll1 > ll2 ? (
              <Col span={10} className="pd5 sub-title">
                <span>{widthCount}</span>
                <span className="mul">X</span>
                <span>{toNumber(realWidth / 10)}</span>
                <span className="mul">=</span>
                <span>{toNumber((widthCount * realWidth) / 10)}</span>
                <span>+</span>
                <span>{toNumber(((widthCount - 1) * diaphragmThickness) / 10)}</span>
                <span>=</span>
                <span>{toNumber(ll2 / 10)}</span>
              </Col>
            ) : (
              <Col span={10} className="pd5 sub-title">
                <span>{lengthCount}</span>
                <span className="mul">X</span>
                <span>{toNumber(realLength / 10)}</span>
                <span className="mul">=</span>
                <span>{toNumber((lengthCount * realLength) / 10)}</span>
                <span>+</span>
                <span>{toNumber(((lengthCount - 1) * diaphragmThickness) / 10)}</span>
                <span>=</span>
                <span>{toNumber(ll1 / 10)}</span>
              </Col>
            )}
          </Row>
          {ll1 > ll2 ? (
            <div className="margin-82px sub-title">
              <span>{lengthCount}</span>
              <span className="mul">X</span>
              <span>{toNumber(realLength / 10)}</span>
              <span className="mul">=</span>
              <span>{toNumber((lengthCount * realLength) / 10.0)}</span>
              <span>+</span>
              <span>{toNumber(((lengthCount - 1) * diaphragmThickness) / 10)}</span>
              <span>=</span>
              <span></span>
              <span>{toNumber(ll1 / 10)}</span>
            </div>
          ) : (
            <div className="margin-82px sub-title">
              <span>{widthCount}</span>
              <span className="mul">X</span>
              <span>{toNumber(realWidth / 10)}</span>
              <span className="mul">=</span>
              <span>{toNumber((widthCount * realWidth) / 10.0)}</span>
              <span>+</span>
              <span>{toNumber(((widthCount - 1) * diaphragmThickness) / 10)}</span>
              <span>=</span>
              <span></span>
              <span>{toNumber(ll2 / 10)}</span>
            </div>
          )}
          <div className="margin-63px mt10 main-title">
            <span className="border-bottom">
              <>
                <span>{aLength}</span>
                <span className="mul">X</span>
                <span>{aWidth}</span>
              </>

              <span className="mul">X</span>
              <span>{aHeight}</span>
              <span className="mul">=</span>
              <span className="ml5">{productNum}只</span>
            </span>
          </div>
          <div className="ml-129 flex margin-95px mt10 sub-title">
            <>
              <div>
                {`${al1}X${aw1}=${al11}`}
                {productNum > 1
                  ? `X${productNum}=${((ll1 > ll2 ? widthCount : lengthCount) - 1) * productNum}`
                  : ''}
              </div>
              <div>
                {`${al2}X${aw2}=${al21}`}
                {productNum > 1
                  ? `X${productNum}=${((ll1 > ll2 ? lengthCount : widthCount) - 1) * productNum}`
                  : ''}
              </div>
            </>
            <div>
              <Button
                onClick={() => {
                  // if(index==)
                  if (select !== index) {
                    setSelect(index);
                  } else {
                    const temp = initCount(param);
                    //@ts-ignore
                    params[index] = temp;
                    setParams([...params]);
                  }
                }}
                type="link"
                className="no-print"
              >
                刷新
              </Button>
              <Button
                onClick={() => {
                  params.splice(select, 1);
                  setParams([...params]);
                  const next = select - 1 < 0 ? 0 : select - 1;
                  setSelect(next);
                }}
                type="link"
                style={{ color: 'red' }}
                className="no-print"
              >
                删除
              </Button>
            </div>
          </div>
        </Col></>
      );
    });
    return (
      <div className="print-page print">
        <div className="no-print">
          <Button
            type="primary"
            onClick={() => {
              window.print();
            }}
          >
            打印
          </Button>
          <Button
            type="primary"
            onClick={() => {
              merge();
            }}
          >
            合并
          </Button>
          <Button
            type="primary"
            onClick={() => {
              refresh();
            }}
          >
            刷新
          </Button>
        </div>
        <div id="print-header">
          <Row className="print-header page-title">
            <Col span={12}>{pageInfo.modelName}</Col>
            <Col span={12}>{pageInfo.date}</Col>
          </Row>
        </div>
        <Row className="no-print page-title">
          <Col span={12}>{pageInfo.modelName}</Col>
          <Col span={12}>{pageInfo.date}</Col>
        </Row>
        <Row gutter={10}>
          {doms}
          <Col span={12}>
            <Button
              className="no-print"
              type="primary"
              onClick={() => {
                const type = params[select]?.type || 0;
                const values = { ...initValues, type };
                form.setFieldsValue(values);
                //@ts-ignore
                const newParams = initCount(values);
                setParams([...params, newParams]);
                setSelect(select + 1);
              }}
            >
              新增
            </Button>
          </Col>
        </Row>
      </div>
    );
  };
  return (
    <div className="page-padding">
      <div className="no-print">
        <ProForm
          form={pageForm}
          onChange={() => {
            const { modelName, date } = pageForm.getFieldsValue();
            setPageInfo({ modelName, date });
          }}
          submitter={false}
        >
          <Row justify="center" gutter={5}>
            <Col span={12}>
              <ProFormText label="规格名称" name="modelName" />
            </Col>
            <Col span={12}>
              <ProFormText label="交货时间" name="date" />
            </Col>
          </Row>
        </ProForm>
        <ProForm
          onChange={() => {
            const type = params[select]?.type;
            params[select] = initCount(form.getFieldsValue());
            if (params[select]) {
              params[select].type = type;
              setParams([...params]);
            }
          }}
          labelWrap={false}
          className="no-print"
          form={form}
          onFinish={() => {
            const value = form.getFieldsValue();
            const pageInfo = pageForm.getFieldsValue();
            // params[select] = initCount({ ...params[select], ...value });
            // setParams([...params]);
            saveJsonData({
              orderId: id,
              jsonData: JSON.stringify({ params, remark: value.remark, ...pageInfo }),
            });
            message.success('保存成功');
          }}
        >
          <Row justify="center" gutter={5}>
            <Col span={4}>
              <ProFormText label="型号" name="model" />
            </Col>
            <Col span={4}>
              <ProFormDigit label="长（mm）" name="length" />
            </Col>
            <Col span={4}>
              <ProFormDigit label="宽（mm）" name="width" />
            </Col>
            <Col span={4}>
              <ProFormDigit label="高（mm）" name="height" />
            </Col>
            <Col span={4}>
              <ProFormDigit label="片数" name="num" />
            </Col>
            <Col span={4}>
              <ProFormDigit label="个数" name="productNum" />
            </Col>
            <Col span={4}>
              <ProFormDigit label="隔板厚度(mm)" name="diaphragmThickness" />
            </Col>
            <Col span={4}>
              <ProFormDigit label="隔板宽差(mm)" name="sideWidth" />
            </Col>
            <Col span={4}>
              <ProFormDigit label="隔板高差(mm)" name="subHeight" />
            </Col>
            <Col span={4}>
              <ProFormText label="长宽最大间距" name="gap" />
            </Col>
            <Col span={4}>
              <ProFormText label="订单备注" name="remark" />
            </Col>
            <Col span={4}>
              <label>规格</label>
              <p style={{ lineHeight: 3.5 }}>
                {types.map((item, index) => (
                  <Tag
                    key={`${index}-tag`}
                    className={`${(params[select]?.type || 0) === index ? 'tag-active' : ''}`}
                    onClick={() => {
                      params[select].type = index;
                      params[select] = initCount(params[select]);
                      setParams([...params]);
                    }}
                  >
                    {item.name}
                  </Tag>
                ))}
              </p>
            </Col>
          </Row>
        </ProForm>
      </div>
      {render(params)}
    </div>
  );
};

export default EditPage;
